<template>
  <div class="staff-container">
    <div class="coffee-bg"></div>
    <div class="header-actions">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i>添加员工
      </el-button>
      <el-input
        v-model="searchQuery"
        placeholder="搜索员工"
        style="width: 200px; margin-left: 16px">
        <template slot="prefix">
          <i class="el-icon-search"></i>
        </template>
      </el-input>
    </div>
    <el-tabs v-model="activeTab" class="staff-tabs coffee-tabs">
      <el-tab-pane label="员工列表" name="list">
        <el-table :data="filteredStaff" style="width: 100%" class="coffee-table">
          <el-table-column prop="id" label="工号" width="100" />
          <el-table-column prop="name" label="姓名" />
          <el-table-column prop="position" label="职位" />
          <el-table-column prop="phone" label="联系电话" />
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === '在职' ? 'success' : 'info'" :class="scope.row.status === '在职' ? 'coffee-tag' : ''">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="primary" @click="handleSchedule(scope.row)">排班</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="排班管理" name="schedule">
        <div class="schedule-container">
          <el-calendar v-model="currentDate" class="coffee-calendar">
            <template slot="dateCell" slot-scope="{ data }">
              <div class="calendar-cell">
                <p>{{ data.day.split('-').slice(2).join('') }}</p>
                <div class="schedule-info">
                  <div v-for="staff in getDaySchedule(data.day)" :key="staff.id" class="staff-schedule coffee-schedule">
                    {{ staff.name }} ({{ staff.shift }})
                  </div>
                </div>
              </div>
            </template>
          </el-calendar>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'add' ? '添加员工' : '编辑员工'"
      width="500px"
      class="coffee-dialog">
      <el-form :model="staffForm" :rules="rules" ref="staffFormRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="staffForm.name" />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-select v-model="staffForm.position">
            <el-option label="咖啡师" value="咖啡师" />
            <el-option label="收银员" value="收银员" />
            <el-option label="店长" value="店长" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="staffForm.phone" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="staffForm.status">
            <el-option label="在职" value="在职" />
            <el-option label="离职" value="离职" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="scheduleDialogVisible"
      title="排班管理"
      width="500px"
      class="coffee-dialog">
      <el-form :model="scheduleForm" :rules="scheduleRules" ref="scheduleFormRef" label-width="100px">
        <el-form-item label="日期" prop="date">
          <el-date-picker v-model="scheduleForm.date" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="班次" prop="shift">
          <el-select v-model="scheduleForm.shift">
            <el-option label="早班 (8:00-16:00)" value="早班" />
            <el-option label="晚班 (16:00-24:00)" value="晚班" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="scheduleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleScheduleSubmit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      searchQuery: '',
      activeTab: 'list',
      dialogVisible: false,
      scheduleDialogVisible: false,
      dialogType: 'add',
      currentDate: new Date(),
      selectedStaff: null,
      staffForm: {
        name: '',
        position: '',
        phone: '',
        status: '在职'
      },
      scheduleForm: {
        date: '',
        shift: '',
        staffId: '',
        staffName: ''
      },
      staff: [],
      schedules: [],
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        position: [
          { required: true, message: '请选择职位', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效手机号', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      scheduleRules: {
        date: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        shift: [
          { required: true, message: '请选择班次', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    filteredStaff() {
      return this.staff.filter(employee =>
        employee.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      )
    }
  },
  created() {
    this.loadStaff()
    this.loadSchedules()
  },
  methods: {
    loadStaff() {
      const local = localStorage.getItem('staff')
      if (local) {
        this.staff = JSON.parse(local)
      }
    },
    loadSchedules() {
      const savedSchedules = localStorage.getItem('staffSchedules')
      if (savedSchedules) {
        this.schedules = JSON.parse(savedSchedules)
      }
    },
    getDaySchedule(day) {
      return this.schedules
        .filter(schedule => schedule.date === day)
        .map(schedule => ({
          id: schedule.staffId,
          name: schedule.staffName,
          shift: schedule.shift
        }))
    },
    handleAdd() {
      this.dialogType = 'add'
      this.staffForm = { name: '', position: '', phone: '', status: '在职' }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogType = 'edit'
      this.staffForm = { ...row }
      this.dialogVisible = true
    },
    handleDelete(row) {
      this.$confirm('确定要删除这个员工吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.staff = this.staff.filter(item => item.id !== row.id)
        localStorage.setItem('staff', JSON.stringify(this.staff))
        this.$message.success('删除成功')
        this.addOperationLog('删除员工', `工号:${row.id} 姓名:${row.name}`)
      }).catch(() => {
        // 用户点击取消按钮时，不执行任何操作
      })
    },
    handleSchedule(row) {
      this.selectedStaff = row
      this.scheduleForm = { 
        date: '', 
        shift: '',
        staffId: row.id,
        staffName: row.name
      }
      this.scheduleDialogVisible = true
    },
    handleSubmit() {
      this.$refs.staffFormRef.validate(valid => {
        if (!valid) return
        if (this.dialogType === 'add') {
          const newStaff = { ...this.staffForm, id: `EMP${Date.now()}` }
          this.staff.push(newStaff)
          localStorage.setItem('staff', JSON.stringify(this.staff))
          this.$message.success('添加成功')
          this.addOperationLog('新增员工', `工号:${newStaff.id} 姓名:${newStaff.name}`)
        } else {
          const index = this.staff.findIndex(item => item.id === this.staffForm.id)
          this.staff.splice(index, 1, { ...this.staffForm })
          localStorage.setItem('staff', JSON.stringify(this.staff))
          this.$message.success('更新成功')
          this.addOperationLog('编辑员工', `工号:${this.staffForm.id} 姓名:${this.staffForm.name}`)
        }
        this.dialogVisible = false
      })
    },
    handleScheduleSubmit() {
      this.$refs.scheduleFormRef.validate(valid => {
        if (!valid) return
        
        // 检查是否已经有相同日期和班次的排班
        const existingSchedule = this.schedules.find(s => 
          s.date === this.formatDate(this.scheduleForm.date) && 
          s.shift === this.scheduleForm.shift
        )
        
        if (existingSchedule) {
          this.$confirm('该时段已有排班，是否替换？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.saveSchedule(true)
          }).catch(() => {})
        } else {
          this.saveSchedule(false)
        }
      })
    },
    saveSchedule(isReplace) {
      const newSchedule = {
        staffId: this.scheduleForm.staffId,
        staffName: this.scheduleForm.staffName,
        date: this.formatDate(this.scheduleForm.date),
        shift: this.scheduleForm.shift
      }

      if (isReplace) {
        const index = this.schedules.findIndex(s => 
          s.date === newSchedule.date && 
          s.shift === newSchedule.shift
        )
        if (index !== -1) {
          this.schedules.splice(index, 1, newSchedule)
        }
      } else {
        this.schedules.push(newSchedule)
      }

      localStorage.setItem('staffSchedules', JSON.stringify(this.schedules))
      this.$message.success('排班成功')
      this.addOperationLog('员工排班', 
        `员工:${newSchedule.staffName} 日期:${newSchedule.date} 班次:${newSchedule.shift}`)
      this.scheduleDialogVisible = false
    },
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    addOperationLog(action, detail) {
      const user = JSON.parse(localStorage.getItem('adminUser') || '{}')
      const logs = JSON.parse(localStorage.getItem('operationLogs') || '[]')
      logs.push({
        time: new Date().toLocaleString(),
        user: user.username || '未知',
        action,
        detail
      })
      localStorage.setItem('operationLogs', JSON.stringify(logs))
    }
  }
}
</script>
<style scoped>
.staff-container {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #e7d2ba 0%, #b08968 100%);
  position: relative;
  overflow: hidden;
}
.coffee-bg {
  position: absolute;
  left: 0; right: 0; top: 0; bottom: 0;
  z-index: 0;
  pointer-events: none;
  background: url('https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/2615.png') repeat 0 0/120px auto;
  opacity: 0.06;
}
.header-actions {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  z-index: 1;
}
.el-button--primary {
  background: linear-gradient(90deg, #a47149 0%, #7c4f22 100%);
  border: none;
  color: #fff;
  font-weight: bold;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(124, 79, 34, 0.08);
  transition: background 0.2s;
}
.el-button--primary:hover {
  background: linear-gradient(90deg, #7c4f22 0%, #a47149 100%);
}
.el-input__inner {
  background: #f8f5f2;
  border-radius: 8px;
  border: 1px solid #e0c3a0;
}
.el-select .el-input__inner {
  background: #f8f5f2;
  border-radius: 8px;
  border: 1px solid #e0c3a0;
}
.coffee-table {
  background: rgba(255,255,255,0.96);
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(124, 79, 34, 0.08);
  overflow: hidden;
}
.coffee-table th, .coffee-table td {
  background: transparent !important;
}
.coffee-tag {
  background: #e7d2ba !important;
  color: #7c4f22 !important;
  border: none !important;
}
.coffee-tabs .el-tabs__item.is-active {
  color: #a47149 !important;
  font-weight: bold;
}
.coffee-tabs .el-tabs__active-bar {
  background: #a47149 !important;
}
.coffee-dialog .el-dialog {
  border-radius: 16px;
  box-shadow: 0 4px 18px 0 rgba(124, 79, 34, 0.10);
  border: 1px solid #e0c3a0;
  background: rgba(255, 255, 255, 0.98);
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.schedule-container {
  margin-top: 20px;
}
.coffee-calendar .el-calendar-table td {
  border-radius: 8px;
  transition: background 0.2s;
}
.coffee-calendar .el-calendar-table td.is-selected {
  background: #e7d2ba !important;
}
.calendar-cell {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.schedule-info {
  font-size: 12px;
  color: #7c4f22;
  margin-top: 4px;
}
.staff-schedule.coffee-schedule {
  margin: 2px 0;
  padding: 2px 6px;
  background-color: #f8f5f2;
  border-radius: 4px;
  color: #a47149;
  font-weight: bold;
  font-size: 13px;
  box-shadow: 0 1px 4px #b0896822;
}
</style> 